package com.kime.email.book;

import javax.mail.*;
import javax.mail.search.AndTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Java 邮件开发详解
 * 搜索并删除符合搜索条件的邮件
 */
public class SearchMailReceives {
    public static void main(String[] args) throws Exception{
        String fromTerm = "newsletter@gradle.com";
        String subjectTerm = "Welcome to the Gradle Newsletter!";
        String pop3Server = "pop.163.com";
        String protocol = "pop3";
        String username = "kimewen@163.com";
        String password = "OTWWWGKLGSAFQPNE";

        Properties properties = new Properties();
        properties.setProperty("mail.store.protocol", protocol);
        properties.setProperty("mail.pop3.host", pop3Server);

        Session mailSession = Session.getDefaultInstance(properties, null);
        mailSession.setDebug(false);

        Store store = mailSession.getStore(protocol);
        store.connect(pop3Server, username, password); // POP3 服务器的登录认证
        Folder folder = store.getFolder("inbox"); // 获得用户的邮件账户
        folder.open(Folder.READ_WRITE); // 设置对邮件账户的访问权限

        SearchTerm searchTerm  = new AndTerm(new FromStringTerm(fromTerm), new SubjectTerm(subjectTerm));
        Message[] messages = folder.search(searchTerm);
        System.out.println("找到"+ messages.length +"封符合搜索条件的邮件\n");
        if (messages.length == 0) {
            System.exit(1);
        }
        for (int i = 0; i < messages.length; i++) {
            String subject = messages[i].getSubject();
            String from = messages[i].getFrom()[0].toString();
            System.out.println("第"+ (i+1) +"封邮件的主题为: " + subject + "\t发件人地址为: " + from);
            System.out.println("你想删除这封邮件吗？(Yes/No)");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = bufferedReader.readLine();
            if ("Yes".equalsIgnoreCase(input)) {
                messages[i].setFlag(Flags.Flag.DELETED, true);
            }
        }
        folder.close(true);
        store.close();
    }
}
